﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;

namespace UIControls
{
    /// <summary>
    /// Interaction logic for TimeInput.xaml
    /// </summary>
    public partial class TimeInput : TextBox
    {
        public TimeInput()
        {
            InitializeComponent();
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            //return;
            TextBox textBox = sender as TextBox;

            Regex r = new Regex(@"^\d\d:\d\d:\d\d$");
            if (r.IsMatch(textBox.Text))
            {
                if (this.GetTime().TotalSeconds < 3)
                {
                    textBox.Text = "00:00:03";
                    textBox.Select(8, 0);
                }
            }
        }

        public TimeSpan GetTime()
        {
            string[] strs = this.Text.Split(':');

            TimeSpan t = new TimeSpan(int.Parse(strs[0]), int.Parse(strs[1]), int.Parse(strs[2]));
            return t;

        }

        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox txt = sender as TextBox;
            if (e.Key == Key.OemSemicolon || e.Key == Key.Enter)
            {
                Regex r = new Regex(@"^\d\d:\d\d:\d\d$");
                if (r.IsMatch(txt.Text))
                {
                    if (this.GetTime().TotalSeconds < 3)
                    {
                        txt.Text = "00:00:03";
                        txt.Select(8, 0);
                    }
                }
                else
                {
                    txt.Text = "00:00:03";
                    txt.Select(8, 0);
                }
                e.KeyboardDevice.ClearFocus();
                return;
            }

            //屏蔽非法按键
            if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal)
            {
                if (txt.Text.Contains(".") && e.Key == Key.Decimal)
                {
                    e.Handled = true;
                    return;
                }
                e.Handled = false;
            }
            else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
            {
                if (txt.Text.Contains(".") && e.Key == Key.OemPeriod)
                {
                    e.Handled = true;
                    return;
                }
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
    }
}
